package config

import (
	"github.com/spf13/viper"
	"strings"
)

func init() {
	LoadAppConfig()
}

type appConfig struct {
	Project   string    `yaml:"project"`
	Redis     Redis     `yaml:"redis"`
	Ks3       Ks3       `yaml:"ks3"`
	RabbitMQ  RabbitMQ  `yaml:"rabbitmq"`
	Upstreams Upstreams `yaml:"upstreams"`
	Services  Services  `yaml:"services"`
}

type Redis struct {
	Addr     string `yaml:"addr"`
	Password string `yaml:"password"`
}

type Ks3 struct {
	Ak       string `yaml:"ak"`
	Sk       string `yaml:"sk"`
	Endpoint string `yaml:"endpoint"`
	Bucket   string `yaml:"bucket"`
}

type RabbitMQ struct {
	Url      string `yaml:"url"`
	Exchange string `yaml:"exchange"`
}

var App *appConfig

func LoadAppConfig() {
	c := viper.New()
	c.SetConfigName("app.yaml")
	c.AddConfigPath("./")
	c.AddConfigPath("./config")
	c.SetConfigType("yaml")
	c.SetEnvPrefix("APP")

	if err := c.ReadInConfig(); err != nil {
		panic(err)
	}
	//NOTICE!!: YAML配置文件中key中不能包含 "_" 因为环境变量使用 "A_B_C" 风格来区分层级
	c.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	c.AutomaticEnv()
	if err := c.Unmarshal(&App); err != nil {
		panic(err)
	}
}
